let db = require('../db/index')
//获取模板所有
exports.getAll = (req, res) => {
  let sql = 'select * from options'
  db.query(sql, (err, data) => {
    if (err) {
      return res.send('错误：' + err.message)
    }
    data.map(item => {
      item.config = JSON.parse(item.config)
      item.lasteidit = JSON.parse(item.lasteidit)
      return item
    })
    res.send({
      status: 200,
      message: 'success',
      data,
    })
  })
}

exports.getById = (req, res) => {
  let sql = `select * from options where id = ?`
  db.query(sql, [req.query.id], (err, data) => {
    if (err) {
      return res.send('错误：' + err.message)
    }
    let tmpArr = JSON.parse(data[0].config)
    let result = {
      data: {
        data: [JSON.parse(tmpArr[0])],
        id: data[0].id
      },
      status: 200,
      message: 'success',
    }
    res.send(result)
  })
}
exports.del = (req, res) => { //通过id删除数据
  let sql = 'delete from options where id = ?'
  db.query(sql, [req.body.id], (err, data) => {
    if (err) {
      return res.send('错误：' + err.message)
    }
    let result = {
      data: {
        status: 200,
        message: 'success',
      }
    }
    res.send(result)
  })
}
//添加
exports.add = (req, res) => {
  console.log(req);
  if (req.body.data.id === -1) {
    let sql = 'insert into options (config,lasteidit,filename) values (?,?,?)'
    let data = JSON.stringify(req.body.data.data)
    db.query(sql, [data,req.body.data.dateTime,req.body.data.fileName], (err, data) => {
      if (err) {
        return res.send('错误：' + err.message)
      }
      let sqls = 'select * from options'
      db.query(sqls, (error, result) => {
        if (error) {
          return error.send('错误：' + error.message)
        }
        let lastId = result[result.length - 1].id
        res.send({
          status: 200,
          message: 'success',
          id: lastId
        })
      })

    })
  } else {
    let sql = `update options set config = ? where id = ?`
    let data = JSON.stringify(req.body.data.data);
    db.query(sql, [data, req.body.data.id], (err, data) => {
      if (err) {
        return res.send('错误：' + err.message)
      }
      let result = {
        data: {
          status: 200,
          message: 'success',
        }
      }
      res.send(result)
    })
  }

}

exports.update = (req, res) => {
  //通过id更新数据
  let sql = `update options set config = ? where id = ?`
  let data = JSON.stringify(req.body.data.data);
  db.query(sql, [data, req.body.data.id], (err, data) => {
    if (err) {
      return res.send('错误：' + err.message)
    }
    let result = {
      data: {
        status: 200,
        message: 'success',
      }
    }
    res.send(result)
    // res.send(data);
  })
}
